package com.xyxy.web;

import com.xyxy.pojo.Cart;
import com.xyxy.pojo.User;
import com.xyxy.service.OrderService;
import com.xyxy.service.impl.OrderServiceImpl;
import sun.management.counter.perf.PerfInstrumentation;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OrderServlet extends BaseServlet {

    private OrderService orderService = new OrderServiceImpl();

    //生成订单
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //先获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //获取userId
        User loginUser = (User) req.getSession().getAttribute("user");
        //如果用户没有登录
        if (loginUser == null) {
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }
        Integer userId = loginUser.getId();

        //调用orderService.createOrder(Cart,Userid)生成订单
        String orderId = orderService.createOrder(cart,userId);
        //将订单号保存到session中
        req.getSession().setAttribute("orderId",orderId);
        //重定向回订单结算界面
        resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");

    }
}
